const { app, BrowserWindow, ipcMain, dialog, remote } = require('electron');
const { autoUpdater } = require('electron-updater')
const path = require('path');
let mainWindow = BrowserWindow.getFocusedWindow()
// 配置清除项
const clearObj = {
  storages: ['appcache', 'filesystem', 'indexdb', 'localstorage', 'shadercache', 'websql', 'serviceworkers', 'cachestorage'],
}

// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) {
  app.quit();
}

const createWindow = () => {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 1420,
    height: 900,
    frame: false,
    // transparent: true,
    autoHideMenuBar: true,
    // show: false,
    icon: path.join(__dirname, 'icons/appIcon.png'),// 窗口图标
    webPreferences: {
      webSecurity: false,//禁用同源策略
      nodeIntegration: true,
      contextIsolation: false,
      nodeIntegrationInWorker: true,
      enableRemoteModule:true,
      preload: path.join(__dirname, 'preload.js'),
    },
  });
  // and load the index.html of the app.
  if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
    mainWindow.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
  } else {
    mainWindow.loadFile(path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`));
  }

  // Open the DevTools.
  mainWindow.webContents.openDevTools();
};

app.commandLine.appendSwitch("disable-site-isolation-trials");

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.


//当一个新的 webContents 被创建时触发。
app.on('web-contents-created',function(event,webContents){
	//当渲染器使用 window.open 打开子窗口 进行拦截配置
	webContents.setWindowOpenHandler((details) => {
		if (details.url) {
			return { 
				action: 'allow',//允许新窗口被创建
				overrideBrowserWindowOptions: {//允许自定义创建的窗口参数
					width: 1100,
          height: 700,
          autoHideMenuBar: true,
          x: 20,
					y: 20,
					resizable: true,
          // show: false,
          icon: path.join(__dirname, 'icons/appIcon.png'),// 窗口图标
          webPreferences: {
            webSecurity: false,//禁用同源策略
            nodeIntegration: true,
            nodeIntegrationInWorker: true,
            enableRemoteModule:true,
            preload: path.join(__dirname, 'preload.js'),
          },
				}
			}
    }
    return { action: 'deny' }//取消创建新窗口
	})
})

// 关闭全部窗口
ipcMain.on('close', () => {
  mainWindow.close()
})
// 重启
ipcMain.on('reload', () => {
  // 重载之后, 刷新并关闭所有之前打开的次要窗体
  if (mainWindow.id === 1) {
    BrowserWindow.getAllWindows().forEach((win) => {
      if (win.id > 1) win.close()
    });
  }
  mainWindow.webContents.session.clearStorageData(clearObj).then(() => {
    mainWindow.reload();
  })
})
// 清除缓存
ipcMain.on('clear', () => {
  mainWindow.webContents.session.clearStorageData(clearObj).then(() => {
    dialog.showMessageBox({
      type: 'info',
      message: '完成清除！'
    })
  })
})
// 窗口最小化
ipcMain.on('min', function () {
  mainWindow.minimize();
})
// 窗口最大化 
ipcMain.on('max', function () {
  if (mainWindow.isMaximized()) {
    mainWindow.unmaximize();
  } else {
    mainWindow.maximize();
  }
  return mainWindow.isMaximized()
})
// 移动窗口
ipcMain.on("move", (_, pos) => {
  mainWindow && mainWindow.setPosition(pos.posX, pos.posY)
});

// 更新
let updateValue = null
ipcMain.on("updated", (_, pos) => {
  autoUpdater.disableWebInstaller = false;
  // 这个写成 false，写成 true 时，可能会报没权限更新
  autoUpdater.autoDownload = false;
  //退出时自动安装更新
  autoUpdater.autoInstallOnAppQuit = false
  // 开发环境测试自动更新使用
  const devUpdatePath = path.join(app.getAppPath(), "..", "dev-update.yml");
  autoUpdater.updateConfigPath = devUpdatePath;
  autoUpdater.forceDevUpdateConfig = true;
  // 每次启动自动更新检查更新版本
  autoUpdater.checkForUpdates();

  autoUpdater.on("error", (error) => {
    console.log(["检查更新失败", error]);
  });
  // 当有可用更新的时候触发。 更新将自动下载。
  autoUpdater.on("update-available", (info) => {
    console.log("检查到有更新，开始下载新版本");
    const { version } = info;
    console.log(`最新版本为： ${version}`);
    updateValue = info
    autoUpdater.downloadUpdate();
  });
  // 当没有可用更新的时候触发，其实就是啥也不用做
  autoUpdater.on("update-not-available", () => {
    updateValue = null
    console.log("没有可用更新");
  });
  // 下载更新包的进度，可以用于显示下载进度与前端交互等
  autoUpdater.on("download-progress", async (progress) => {
    console.log(progress, 'downloadPercent');
    // console.log(progress);
    // 计算下载百分比
    const downloadPercent = Math.round(progress.percent * 100) / 100;
    // 实时同步下载进度到渲染进程，以便于渲染进程显示下载进度
    downloadProgress = downloadPercent
  });
  // 在更新下载完成的时候触发。
  autoUpdater.on("update-downloaded", (res) => {
    console.log("下载完毕, 提示安装更新", res);
    dialog.showMessageBox({
      type: 'warning',
      title: '更新提示',
      message: '下载完成',
      buttons: ['更新', '取消'],
      cancelId: 1
    }).then(res => {
      if (res.response == 0) {
        // 下载完成之后，关闭所有窗口开始更新
        autoUpdater.quitAndInstall()
      }
    })
  });
});